package me.yiyou.meihua.utils

import com.google.gson.Gson
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import me.yiyou.meihua.data.xinghuo.XHFlowResponse
import okhttp3.ResponseBody
import okio.Buffer


/**
 * 流式布局解析器
 */
object XHResponseParser {

    // 解析流式响应为Flow
    fun parseStreamResponse(body: ResponseBody): Flow<ParseResult> = flow {
        val source = body.source()
        val buffer = Buffer()

        try {
            while (!source.exhausted()) {
                val line = source.readUtf8Line() ?: continue

                when {
                    line.isBlank() -> continue
                    line == "data: [DONE]" -> {
                        emit(ParseResult.Complete)
                        break
                    }

                    line.startsWith("data: ") -> {
                        val json = line.substring(6) // 移除"data: "前缀
                        parseJsonChunk(json)?.let { emit(it) }
                    }
                }
            }
        } catch (e: Exception) {
            emit(ParseResult.Error(e))
        } finally {
            buffer.close()
        }
    }

    private fun parseJsonChunk(json: String): ParseResult? {
        return try {
            val response = Gson().fromJson(json, XHFlowResponse::class.java)

            // 检查状态码
            if (response.code != 0) {
                return ParseResult.Error(Exception("API Error: ${response.message}"))
            }

            response.choices.firstOrNull()?.getContent()?.let {
                ParseResult.Chunk(it)
            }
        } catch (e: Exception) {
            ParseResult.Error(e)
        }
    }

    sealed class ParseResult {
        data class Chunk(val content: String) : ParseResult()
        object Complete : ParseResult()
        data class Error(val exception: Throwable) : ParseResult()
    }
}